package com.example.kyyl.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleMtuChangedCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleRssiCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.clj.fastble.utils.HexUtil;
import com.example.kyyl.R;
import com.example.kyyl.adapter.DeviceAdapter;
import com.example.kyyl.comm.ObserverManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import static com.clj.fastble.exception.BleException.ERROR_CODE_GATT;
import static com.clj.fastble.exception.BleException.ERROR_CODE_OTHER;
import static com.clj.fastble.exception.BleException.ERROR_CODE_TIMEOUT;


public class BloodPressMearActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String servicefff0uuid = "0000fff0-0000-1000-8000-00805f9b34fb";
    public static final String servicefff4duuid = "0000fff4-0000-1000-8000-00805f9b34fb";
    private static final String TAG = BloodPressMearActivity.class.getSimpleName();
    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    public TextView pb_txt_setting;
    public TextView pb_measure_result;
    public Timer timer = new Timer();
    public int icount = 1;
    private TextView btn_scan;
    private Animation operatingAnim;
    private DeviceAdapter mDeviceAdapter;
    private ProgressDialog progressDialog;
    private String userId = "111";
    private ImageView pb_backButton;
    private ImageView img_loading;
    private boolean isItemDis = false; //判断是点击返回还是点击设备item
    private boolean isConnected = false; //判断是否有链接的设备
    private boolean isRuned = false; //判断是否是上次测量过血压结果，避免血压计在测量结果页面直接跳转到显示结果页面

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blood_press_mear);
        initView();

        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 5000)
                .setConnectOverTime(20000)
                .setOperateTimeout(5000);

        checkPermissions();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private void initView() {

        btn_scan = findViewById(R.id.btn_scan);
        btn_scan.setText(getString(R.string.start_scan));
        btn_scan.setOnClickListener(this);

        pb_txt_setting = findViewById(R.id.measure_press_device);
        this.pb_measure_result = findViewById(R.id.measure_bp_result);
        this.pb_backButton = (ImageView) findViewById(R.id.loan_back_press);
        this.pb_backButton.setOnClickListener(this);

        img_loading = (ImageView) findViewById(R.id.img_loading);


        operatingAnim = AnimationUtils.loadAnimation(this, R.anim.rotate);
        operatingAnim.setInterpolator(new LinearInterpolator());
        progressDialog = new ProgressDialog(this);

        mDeviceAdapter = new DeviceAdapter(this);
        mDeviceAdapter.setOnDeviceClickListener(new DeviceAdapter.OnDeviceClickListener() {
            @Override
            public void onConnect(BleDevice bleDevice) {
                if (!BleManager.getInstance().isConnected(bleDevice)) {
                    BleManager.getInstance().cancelScan();
                    connect(bleDevice);
                }
            }

            @Override
            public void onDisConnect(final BleDevice bleDevice) {
                if (BleManager.getInstance().isConnected(bleDevice)) {
                    isItemDis = true;
                    BleManager.getInstance().disconnect(bleDevice);
                }
            }

            @Override
            public void onDetail(BleDevice bleDevice) {
                if (BleManager.getInstance().isConnected(bleDevice)) {
//                    Intent intent = new Intent(MainActivity.this, OperationActivity.class);
//                    intent.putExtra(OperationActivity.KEY_DATA, bleDevice);
//                    startActivity(intent);
                }
            }
        });
        ListView listView_device = findViewById(R.id.list_device);
        listView_device.setAdapter(mDeviceAdapter);
    }

    private void connect(final BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                progressDialog.setTitle("正在连接...");
                progressDialog.show();
                BloodPressMearActivity.this.pb_txt_setting.setText("连接中...");

            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException bleException) {
                stopLoading();
                progressDialog.dismiss();
                Toast.makeText(BloodPressMearActivity.this, getString(R.string.connect_fail), Toast.LENGTH_LONG).show();
                if (bleException.getCode() == ERROR_CODE_TIMEOUT) {
                    BloodPressMearActivity.this.pb_txt_setting.setText("连接超时，点击查询设备选择蓝牙设备重新连接");
                } else if (bleException.getCode() == ERROR_CODE_GATT) {
                    BloodPressMearActivity.this.pb_txt_setting.setText("错误的蓝牙特征，请重新选择蓝牙");
                } else if (bleException.getCode() == ERROR_CODE_OTHER) {
                    BloodPressMearActivity.this.pb_txt_setting.setText("连接失败，请重新连接,错误信息：" + bleException.getDescription());
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                isConnected = true;
                progressDialog.dismiss();
                mDeviceAdapter.addDevice(bleDevice);
                mDeviceAdapter.notifyDataSetChanged();
                listenToNotify(bleDevice, gatt);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
                isConnected = false;
                progressDialog.dismiss();
                BloodPressMearActivity.this.pb_txt_setting.setText(R.string.disconnect);

                mDeviceAdapter.removeDevice(bleDevice);
                mDeviceAdapter.notifyDataSetChanged();

                if (isActiveDisConnected) {
                    Toast.makeText(BloodPressMearActivity.this, getString(R.string.active_disconnected), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(BloodPressMearActivity.this, getString(R.string.disconnected), Toast.LENGTH_LONG).show();
                    ObserverManager.getInstance().notifyObserver(bleDevice);
                }

                if (isItemDis) {
                    startScan();
                } else {
                    finish();
                }
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void listenToNotify(final BleDevice bleDevice, BluetoothGatt bluetoothGatt) {
        final BluetoothGattCharacteristic characteristic = bluetoothGatt.getService(UUID.fromString(servicefff0uuid)).getCharacteristic(UUID.fromString(servicefff4duuid));
        BleManager.getInstance().notify(bleDevice, characteristic.getService().getUuid().toString(), characteristic.getUuid().toString(), new BleNotifyCallback() {
            public void onNotifySuccess() {
                BloodPressMearActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        BloodPressMearActivity.this.pb_txt_setting.setText(R.string.connected);
                        BloodPressMearActivity.this.pb_measure_result.setVisibility(View.VISIBLE);
                    }
                });
            }

            public void onNotifyFailure(BleException bleException) {
                BloodPressMearActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                    }
                });
            }

            public void onCharacteristicChanged(byte[] bArr) {
                BloodPressMearActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            String[] split = HexUtil.formatHexString(characteristic.getValue(), true).split(" ");
                            Log.i("数据接收1", split[0] + split[1] + split[2]);
                            if (split[2].contains("05")) {
                                BloodPressMearActivity.this.pb_txt_setting.setText(R.string.measure_bg_device_sucess);
                                final Integer valueOf = Integer.valueOf(Integer.parseInt(split[6], 16));
                                BloodPressMearActivity.this.pb_measure_result.setVisibility(View.VISIBLE);
                                BloodPressMearActivity.this.timer.schedule(new TimerTask() {
                                    public void run() {
                                        isRuned = true;
                                        BloodPressMearActivity.this.pb_measure_result.setText(valueOf.toString());
                                    }
                                }, 500);
                            } else if (!split[2].contains("08")) {
                            } else {

                                if (BloodPressMearActivity.this.icount > 1) {
                                    BleManager.getInstance().stopNotify(bleDevice, characteristic.getService().getUuid().toString(), characteristic.getUuid().toString());
                                    BleManager.getInstance().disconnectAllDevice();
                                    BleManager.getInstance().destroy();
                                    return;
                                }
                                String[] split2 = HexUtil.formatHexString(characteristic.getValue(), true).split(" ");
                                String str = split2[6];
                                Log.i("数据接收高压", str);
                                String str2 = split2[8];
                                Log.i("数据接收低压", str2);
                                String str3 = split2[9];
                                Log.i("数据接收心率", str3);
                                //                            SPUtil.putString(BloodPressMearActivity.this,"gaoya",str);
                                //                            SPUtil.putString(BloodPressMearActivity.this,"gaoya",str);
                                //                            SPUtil.putString(BloodPressMearActivity.this,"gaoya",str);
                                Integer[] numArr = {Integer.valueOf(Integer.parseInt(str, 16)), Integer.valueOf(Integer.parseInt(str2, 16)), Integer.valueOf(Integer.parseInt(str3, 16))};
                                String str4 = numArr[0].toString() + "," + numArr[1].toString() + "," + numArr[2].toString();
                                Log.i("数据接收2", str4);
                                BloodPressMearActivity.this.startMeasureResultAct(str4);
                                Log.i("stopnotify", "stop");
                            }
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

    /* access modifiers changed from: private */
    public void startMeasureResultAct(String str) {
        Intent intent = new Intent(this, MeasurePressResultActivity.class);
        String[] split = str.split(",");
        intent.putExtra("bloodpress1", split[0]);
        intent.putExtra("bloodpress2", split[1]);
        intent.putExtra("bloodpress3", split[2]);
        intent.putExtra("userid", this.userId);
        Log.i("userid", this.userId);
        if (this.icount == 1) {
            if (isRuned) {
                startActivity(intent);
                this.icount = 2;
                isRuned = false;
            } else {
                BloodPressMearActivity.this.pb_txt_setting.setText("请重启血压计");
//                Toast.makeText(this, "请重启血压计", Toast.LENGTH_LONG).show();

            }

            return;
        }
        sendBoard(split);
    }

    private void sendBoard(String[] strArr) {
        Intent intent = new Intent();
        intent.setAction("action.refreshPress");
        intent.putExtra("bloodpress1", strArr[0]);
        intent.putExtra("bloodpress2", strArr[1]);
        intent.putExtra("bloodpress3", strArr[2]);
        sendBroadcast(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_scan:
                if (btn_scan.getText().equals(getString(R.string.start_scan))) {
                    checkPermissions();
                } else if (btn_scan.getText().equals(getString(R.string.stop_scan))) {
                    stopLoading();
                    BleManager.getInstance().cancelScan();
                }
                break;
            case R.id.loan_back_press:
                stopLoading();
                if (isConnected) {
                    progressDialog.setTitle("正在断开连接...");
                    progressDialog.show();
                    isItemDis = false;
                    BleManager.getInstance().disconnectAllDevice();
                    BleManager.getInstance().destroy();
                } else {
                    finish();
                }
                break;


        }
    }

    private void checkPermissions() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
            return;
        }

        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void stopLoading() {
        img_loading.clearAnimation();
        img_loading.setVisibility(View.INVISIBLE);
        btn_scan.setText(getString(R.string.start_scan));
    }

    private void onPermissionGranted(String permission) {
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
                    new AlertDialog.Builder(this)
                            .setTitle(R.string.notifyTitle)
                            .setMessage(R.string.gpsNotifyMsg)
                            .setNegativeButton(R.string.cancel,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    })
                            .setPositiveButton(R.string.setting,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
                                        }
                                    })

                            .setCancelable(false)
                            .show();
                } else {
                    setScanRule();
                    startScan();
                }
                break;
        }
    }

    private boolean checkGPSIsOpen() {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null)
            return false;
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    private void setScanRule() {
        String[] uuids;
        if (TextUtils.isEmpty(servicefff0uuid)) {
            uuids = null;
        } else {
            uuids = servicefff0uuid.split(",");
        }
        UUID[] serviceUuids = null;
        if (uuids != null && uuids.length > 0) {
            serviceUuids = new UUID[uuids.length];
            for (int i = 0; i < uuids.length; i++) {
                String name = uuids[i];
                String[] components = name.split("-");
                if (components.length != 5) {
                    serviceUuids[i] = null;
                } else {
                    serviceUuids[i] = UUID.fromString(uuids[i]);
                }
            }
        }


        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setServiceUuids(serviceUuids)      // 只扫描指定的服务的设备，可选
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
    }

    private void startScan() {
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                mDeviceAdapter.clearScanDevice();
                mDeviceAdapter.notifyDataSetChanged();
                img_loading.startAnimation(operatingAnim);
                img_loading.setVisibility(View.VISIBLE);
                btn_scan.setText(getString(R.string.stop_scan));
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                mDeviceAdapter.addDevice(bleDevice);
                mDeviceAdapter.notifyDataSetChanged();

            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                stopLoading();
            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);

            }
        });
    }

    private void readRssi(BleDevice bleDevice) {
        BleManager.getInstance().readRssi(bleDevice, new BleRssiCallback() {
            @Override
            public void onRssiFailure(BleException exception) {
                Log.i(TAG, "onRssiFailure" + exception.toString());
            }

            @Override
            public void onRssiSuccess(int rssi) {
                Log.i(TAG, "onRssiSuccess: " + rssi);
            }
        });
    }

    private void setMtu(BleDevice bleDevice, int mtu) {
        BleManager.getInstance().setMtu(bleDevice, mtu, new BleMtuChangedCallback() {
            @Override
            public void onSetMTUFailure(BleException exception) {
                Log.i(TAG, "onsetMTUFailure" + exception.toString());
            }

            @Override
            public void onMtuChanged(int mtu) {
                Log.i(TAG, "onMtuChanged: " + mtu);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_GPS) {
            if (checkGPSIsOpen()) {
                setScanRule();
                startScan();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        showConnectedDevice();
    }

    @Override
    public final void onRequestPermissionsResult(int requestCode,
                                                 @NonNull String[] permissions,
                                                 @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION_LOCATION:
                if (grantResults.length > 0) {
                    for (int i = 0; i < grantResults.length; i++) {
                        if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                            onPermissionGranted(permissions[i]);
                        }
                    }
                }
                break;
        }
    }

    private void showConnectedDevice() {
        List<BleDevice> deviceList = BleManager.getInstance().getAllConnectedDevice();
        mDeviceAdapter.clearConnectedDevice();
        for (BleDevice bleDevice : deviceList) {
            mDeviceAdapter.addDevice(bleDevice);
        }
        mDeviceAdapter.notifyDataSetChanged();
    }

}
